<?php
/**
 * User: taodf
 * Date: 17-4-29
 * Time: 下午2:25
 */

namespace Zeus\View\Engines;

use MtHaml\Environment;
use MtHaml\Support\Php\Executor as Haml;
use Zeus\View\Exceptions\NotImplementedException;

class HamlEngine implements EngineInterface
{
    /**
     * Haml引擎
     *
     * @var Haml $engine
     */
    private $engine;

    /**
     * 模板根目录
     *
     * @var string $path
     */
    private $path;

    /**
     * 视图参数
     *
     * @var array $param
     */
    private $param;

    /**
     * 模板文件
     *
     * @var string $view
     */
    private $view;

    public function __construct($path)
    {
        $this->path=$path;
        $this->engine=new Haml(
            new Environment("php"), ["cache"=>$path."/cache/haml"]
        );
    }

    /**
     * 使用视图引擎渲染试图文件
     *
     * @param string $view
     * @param array $param
     * @return string
     */
    public function render($view, $param = [])
    {
        $this->view=$view;
        if(!is_null($param)){
            $param=array_merge($this->param, $param);
        }
        return $this->engine->render(
            $this->path.DIRECTORY_SEPARATOR.$view, $param
        );
    }

    /**
     * 向视图引擎中注入变量
     *
     * @param string $name
     * @param mixed $value
     * @return mixed
     */
    public function with($name, $value)
    {
        $this->param=array_merge($this->param, [$name=>$value]);
        return $this;
    }

    /**
     * 向视图引擎全局空间注入变量
     *
     * @param string $name
     * @param mixed $value
     * @return null
     * @throws NotImplementedException
     */
    public function share($name, $value)
    {
        throw new NotImplementedException();
    }

    /**
     * 向视图引擎中添加新的模板目录
     *
     * @param string $name
     * @param string $path
     * @return null
     * @throws NotImplementedException
     */
    public function names($name, $path)
    {
        throw new NotImplementedException();
    }

    /**
     * 为视图引擎注册新的功能
     *
     * @param string $name
     * @param callable $callable
     * @return null
     * @throws NotImplementedException
     */
    public function feature($name, $callable)
    {
        throw new NotImplementedException();
    }

    /**
     * 渲染模板文件
     *
     * @return string
     */
    public function __toString()
    {
        return $this->render($this->view, $this->param);
    }
}